package cn.edu.fzu.homemaking.sso.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.edu.fzu.homemaking.common.SessionConstant;
import cn.edu.fzu.homemaking.sso.domain.entity.SysUser;
import cn.edu.fzu.homemaking.sso.service.ResourceService;
import cn.edu.fzu.homemaking.web.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import cn.edu.fzu.homemaking.sso.domain.entity.User;
import cn.edu.fzu.homemaking.sso.domain.enums.StatusEnum;

@Api(tags = "SSO-资源管理模块")
@RestController
@RequestMapping("/api/sso/auth/resource")
public class ResourceController {

    @Resource
    private ResourceService resourceService;

    @ApiOperation(value = "查询资源", httpMethod = "GET")
    @ApiImplicitParams({ @ApiImplicitParam(name = "name", required = true, value = "资源名称"),
            @ApiImplicitParam(name = "pid", required = true, value = "父级资源id"),
            @ApiImplicitParam(name = "status", required = true, value = "状态") })
    @GetMapping("/list")
    public Result list(@RequestParam(required = false) String name, @RequestParam(required = false) Long pid,
                       @RequestParam(required = false) StatusEnum status, HttpServletRequest request) {

        User currentUser = (User) request.getSession().getAttribute(SessionConstant.ACCOUNT);
        Long userId = null;
        if (!(currentUser instanceof SysUser)) {
            userId = currentUser.getId();
        }
        return new Result(resourceService.list(userId, name, pid, status, true));
    }


    /** 授权 角色相关资源 **/
    @ApiOperation(value = "给角色授权相关资源", httpMethod = "POST")
    @ApiImplicitParams({ @ApiImplicitParam(name = "roleId", required = true, value = "角色id"),
            @ApiImplicitParam(name = "resourceIds", required = true, value = "资源集合，逗号分割") })
    @PostMapping("/grant")
    public Result grant(@RequestParam Long roleId, @RequestParam List<Long> resourceIds) {
        resourceService.grant(roleId, resourceIds);
        return Result.SUCCESS;
    }


    @ApiOperation(value = "根据角色id查询角色拥有的资源id", httpMethod = "GET")
    @ApiImplicitParams({ @ApiImplicitParam(name = "roleId", required = true, value = "角色id") })
    @GetMapping("/getRoleResources")
    public Result listResourceIdByRoleId(Long roleId) {
        return new Result(resourceService.listResourceIdByRoleId(roleId));
    }
}
